module.exports = app =>{
    const express = require('express')
    const assert = require('http-assert')
    const User =  require('../../models/System/User')
    const UserLoginLog =  require('../../models/Common/UserLoginLog')
    const jwt = require('jsonwebtoken')
    const session = require('express-session')
    const svgCaptcha = require("svg-captcha")

    // 使用express-session 来存放数据到session中
    app.use(
        session({
            secret: 'luckystar',
            name: 'captcha',
            resave: false,
            saveUninitialized: true,
            cookie: { maxAge: 50000 },
            rolling: true,
        })
    )
    const router = express.Router({ 
        mergeParams:true,
    })
    // 登录校验中间件
    const authMiddleware = require('../../middleware/auth')
    // 上传图片中间件
    const resourceMiddleware = require('../../middleware/resource')
    // 用户信息校验中间件
    const userIpMiddleware = require('../../middleware/userIp')
    // 数据大屏中间件
    const dataScreenMiddleware = require('../../middleware/dataScreen')
    
    //  资源列表
    router.post('/list',async(req,res)=>{
        var count=0;
        var page=req.body.page;
        var rows=req.body.rows;
        
        var essayType = req.body.essayType; // 文章类型
        var essayState = req.body.essayState; // 文章状态
        var essayTitle  = req.body.title // 文章标题模糊查询
        var essayTag = req.body.essayTag // 文章标签

        // 模糊查询
        var reg = new RegExp(essayTitle,'i');
        let queryObj = essayTitle ? { title : {$regex : reg} } : {}
        var query=req.Model.find(queryObj);
        query.skip((page-1)*rows);
        query.limit(rows);

        // 条件查询
        essayState ? query.where('essayState',essayState) : ''
        essayType ? query.where('essayType',essayType) : ''
        essayTag ? query.where('essayTag',essayTag) : ''
        //计算分页数据
        query.exec(function(err,rs){
            if(err){
                res.send(err);
            }else{
                //计算数据总数
                req.Model.find(function(err,result){
                    jsonArray={rows:rs,total:result.length};
                    res.json(jsonArray);
                });
                
            }
        }); 
        
    })
    // 新增资源
    router.post('/add',async(req,res)=>{
        assert(req.role, 500, '访客模式，不支持操作！') 
        req.body.createTime = new Date()
        const model = await req.Model.create(req.body)
        res.send(model)
     })
    // 删除资源
    router.post('/delete',async(req,res)=>{
        assert(req.role, 500, '访客模式，不支持操作！')
        const model = await req.Model.findByIdAndDelete(req.body.id)
        res.send(model)
     })
    //  根据id获取单个资源
     router.post('/findOne',async(req,res)=>{
         const model = await req.Model.findById(req.body.id)
         if(req.body.pageView){
            model.pageView++
            await req.Model.findByIdAndUpdate(req.body.id,model)
         }
         res.send(model)
     })
    //  修改资源
     router.post('/update',async(req,res)=>{
        assert(req.role, 500, '访客模式，不支持操作！')
        req.body.updateTime = new Date()
         const model = await req.Model.findByIdAndUpdate(req.body.id,req.body)
         res.send(model)
     })
     
    app.use('/admin/api/rest/:sort/:resource',authMiddleware(),resourceMiddleware(),router) 

    // 上传
    const multer = require('multer')
    const upload = multer({ dest: __dirname + '/../../uploads'})
    app.post('/admin/api/upload',authMiddleware(),upload.single('file'),async(req,res)=>{
        assert(req.role, 500, '访客模式，不支持操作！') 
        const file = req.file
        file.url = `http://blog.lhzzs.top/uploads/${file.filename}`
        // file.url = `http://localhost:9001/uploads/${file.filename}`
        res.send(file)
    })
    // 登录校验二维码
    app.get('/admin/api/login/img_code', (req, res) => {
        const captcha = svgCaptcha.createMathExpr({
            mathMin:0,
            mathMax:9,
            background: '#cc9',
            mathOperator:'+-'
        })
        // 将图片的验证码存入到 session 中
        req.session.imgLoginCode = captcha.text
        res.type('svg');
        res.send(captcha.data);
    })
    // 注册校验二维码
    app.get('/admin/api/register/img_code', (req, res) => {
        const captcha = svgCaptcha.createMathExpr({
            mathMin:0,
            mathMax:9,
            background: '#cc9',
            mathOperator:'+-'
        })
        // 将图片的验证码存入到 session 中
        req.session.imgRegisterCode = captcha.text 
        res.type('svg');
        res.send(captcha.data);
    })
    // 注册
    app.post(('/admin/api/register'),async (req,res)=>{
        const { imgCode } = req.body
        // img_code 获取传递的图片验证码 ,如果不相等，验证码错误
        assert(imgCode.toLocaleUpperCase() === req.session.imgRegisterCode, 422, '验证码错误')
         // 新增用户防止用户名重复
         const userName = req.body.userName
         if(userName){
             const isUser = await User.findOne({userName})
             assert(!isUser, 500, '用户已存在')
         }
        await User.create(req.body)
        res.send(req.body)
    })
    // 登录
    app.post('/admin/api/login',userIpMiddleware(),async (req,res)=>{
        // 新增登录日志
        const loginTime = new Date()
        const {createTime, updateTime, userSite,  userIp, userCity, role, userName, nickName,phoneNumber, email,userPic,sex,remark} = req.user
        let passName = '管理系统' // 平台名称
        const moudle =await  UserLoginLog.create({passName,loginTime,createTime, updateTime, userSite,  userIp, userCity, role, userName, nickName,phoneNumber, email,userPic,sex,remark})
        // 登录成功，返回token
        res.send({token:req.token})
    })
    // 用户信息
    app.post(('/admin/api/userInfo'),authMiddleware(),async (req,res)=>{
        res.send(req.user)
    }) 
    // 数据大屏信息
    app.post(('/admin/api/dataScreen'),authMiddleware(),dataScreenMiddleware(),async (req,res)=>{
        res.send({data:req.dataScreenObj})
    })
    // 错误处理函数
    app.use(async (err, req, res, next) => {
        // console.log(err)
        res.status(err.statusCode || 500).send({
        message: err.message
        })
    })

}
    